<template>
  <div class="home-page">
    <!-- 背景动画层 -->
    <div class="background-layer">
      <div class="cyber-grid"></div>
      <div class="floating-particles"></div>
    </div>

    <!-- 主要内容 -->
    <div class="main-content">
      <!-- 页面头部 -->
      <header class="page-header">
        <div class="header-content">
          <div class="logo-section">
            <h1 class="site-title">
              <span class="title-text">Trae 智能体分享平台</span>
              <span class="title-subtitle">Trae Agent Share Platform</span>
            </h1>
          </div>
          
          <div class="header-actions">
            <el-button
              v-show="false"
              @click="openTagManagementDialog"
              class="management-btn"
              size="large"
            >
              <el-icon><Collection /></el-icon>
              标签管理
            </el-button>
            <el-button
              v-show="false"
              @click="openClassifyManagementDialog"
              class="management-btn"
              size="large"
            >
              <el-icon><FolderOpened /></el-icon>
              分类管理
            </el-button>
            <el-button
              type="primary"
              @click="openRegisterDialog"
              class="register-btn"
              size="large"
            >
              添加智能体
            </el-button>
          </div>
        </div>
      </header>

      <!-- 搜索和筛选区域 -->
      <section class="search-section">
        <div class="search-container">
          <div class="search-bar">
            <el-input
              v-model="searchQuery"
              placeholder="搜索智能体名称、描述或标签..."
              size="large"
              clearable
              class="search-input"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          
          <div class="filter-bar">
            <el-select
              v-model="selectedCategory"
              placeholder="选择分类"
              clearable
              class="category-select"
            >
              <el-option label="全部分类" value="" />
              <el-option
                v-for="category in categories"
                :key="category.value"
                :label="category.label"
                :value="category.value"
              />
            </el-select>
            
            <el-select
              v-model="sortBy"
              placeholder="排序方式"
              class="sort-select"
            >
              <el-option label="最新创建" value="createdAt" />
              <el-option label="最近更新" value="updatedAt" />
              <el-option label="名称排序" value="name" />
              <el-option label="作者排序" value="author" />
            </el-select>
          </div>
        </div>
      </section>

      <!-- 统计信息 -->
      <section class="stats-section">
        <div class="stats-container">
          <div class="stat-item">
            <div class="stat-number">{{ totalAgents }}</div>
            <div class="stat-label">智能体总数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ filteredAgents.length }}</div>
            <div class="stat-label">当前显示</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ categories.length }}</div>
            <div class="stat-label">分类数量</div>
          </div>
        </div>
      </section>

      <!-- 智能体列表 -->
      <section class="agents-section">
        <div class="section-header">
          <h2 class="section-title">智能体列表</h2>
          <div class="view-controls">
            <el-button-group>
              <el-button
                :type="viewMode === 'grid' ? 'primary' : 'default'"
                @click="viewMode = 'grid'"
                size="small"
              >
                <el-icon><Grid /></el-icon>
              </el-button>
              <el-button
                :type="viewMode === 'list' ? 'primary' : 'default'"
                @click="viewMode = 'list'"
                size="small"
              >
                <el-icon><List /></el-icon>
              </el-button>
            </el-button-group>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="6" animated class="skeleton-item" />
        </div>

        <!-- 空状态 -->
        <div v-else-if="filteredAgents.length === 0" class="empty-state">
          <div class="empty-icon">
            <el-icon :size="64"><DocumentAdd /></el-icon>
          </div>
          <h3 class="empty-title">暂无智能体</h3>
          <p class="empty-description">
            {{ searchQuery || selectedCategory ? '没有找到符合条件的智能体' : '还没有注册任何智能体' }}
          </p>
          <el-button
            v-if="!searchQuery && !selectedCategory"
            type="primary"
            @click="openRegisterDialog"
            class="empty-action"
          >
            立即注册第一个智能体
          </el-button>
        </div>

        <!-- 智能体网格/列表 -->
        <div
          v-else
          :class="[
            'agents-container',
            `view-${viewMode}`
          ]"
        >
          <TransitionGroup
            name="agent-card"
            tag="div"
            class="agents-grid"
          >
            <AgentCard
              v-for="agent in paginatedAgents"
              :key="agent.id"
              :agent="agent"
              :view-mode="viewMode"
              @edit="handleEditAgent"
              @delete="handleDeleteAgent"
              @export="handleExportAgent"
              @copy="handleCopyAgent"
              class="agent-card-item"
            />
          </TransitionGroup>
        </div>

        <!-- 分页 -->
        <div v-if="totalPages > 1" class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="filteredAgents.length"
            :page-sizes="[12, 24, 48, 96]"
            layout="total, sizes, prev, pager, next, jumper"
            background
            class="pagination"
            @size-change="handleSizeChange"
          />
        </div>
      </section>
    </div>

    <!-- 注册/编辑弹窗 -->
    <RegisterDialog
      v-model="registerDialogVisible"
      :agent="selectedAgent"
      @submit="handleRegisterSubmit"
      @edit="handleEditSubmit"
    />

    <!-- 错误处理组件 -->
    <ErrorHandler
      v-if="networkError"
      :error="networkError"
      @retry="handleRetry"
      @close="clearNetworkError"
    />

    <!-- 删除确认弹窗 -->
    <DeleteConfirmDialog
      v-model="deleteDialogVisible"
      :agent-name="selectedAgent?.name"
      :agent-id="selectedAgent?.id"
      @confirm="handleDeleteConfirm"
    />

    <!-- 返回顶部按钮 -->
    <el-backtop :right="40" :bottom="40" />
  </div>

  <!-- 标签管理对话框 -->
  <TagManagementDialog 
    :visible="tagManagementDialogVisible"
    @update:visible="tagManagementDialogVisible = $event"
    @tag-updated="handleTagsUpdated"
  />

  <!-- 分类管理对话框 -->
  <ClassifyManagementDialog 
    v-model="classifyManagementDialogVisible"
    @classifiesUpdated="handleClassifiesUpdated"
  />
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Grid,
  List,
  DocumentAdd,
  Collection,
  FolderOpened
} from '@element-plus/icons-vue'
import TagManagementDialog from '@/components/TagManagementDialog.vue'
import ClassifyManagementDialog from '@/components/ClassifyManagementDialog.vue'
import type { Agent, CreateAgentInput } from '@/types/agent'
import { useAgents } from '@/composables/useAgents'
import { useDialog } from '@/composables/useDialog'
import { useNetworkStatus } from '@/composables/useNetworkStatus'
import { updateAgent } from '@/services/dataService'
import AgentCard from '@/components/AgentCard.vue'
import RegisterDialog from '@/components/RegisterDialog.vue'
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue'
import ErrorHandler from '@/components/ErrorHandler.vue'
import {
  animatePageEnter,
  animateListEnter,
  animateButtonClick
} from '@/services/animationService'

// 组合式函数
const {
  agents,
  loading,
  error,
  agentCount,
  hasAgents,
  sortedAgents,
  loadAgentsData,
  addAgent,
  deleteAgent,
  searchAgents,
  exportData,
  clearError,
  // 网络状态
  isOnline,
  networkError,
  retryRequest
} = useAgents()

const {
  registerDialogVisible,
  deleteDialogVisible,
  openDeleteConfirmDialog
} = useDialog()

// 编辑对话框状态（复用注册弹窗）
// const editDialogVisible = ref(false) // 已删除，复用registerDialogVisible

// 网络状态管理
const { clearNetworkError } = useNetworkStatus()

// 响应式数据
const searchQuery = ref('')
const selectedCategory = ref('')
const sortBy = ref('createdAt')
const viewMode = ref<'grid' | 'list'>('grid')
const currentPage = ref(1)
const pageSize = ref(12)
const selectedAgent = ref<Agent | null>(null)

// 管理对话框状态
const tagManagementDialogVisible = ref(false)
const classifyManagementDialogVisible = ref(false)

// 分类选项（响应式）
const categories = ref([
  { label: '编程助手', value: 'programming' },
  { label: '写作助手', value: 'writing' },
  { label: '数据分析', value: 'data-analysis' },
  { label: '创意设计', value: 'design' },
  { label: '教育培训', value: 'education' },
  { label: '商务办公', value: 'business' },
  { label: '生活服务', value: 'lifestyle' },
  { label: '其他', value: 'other' }
])

// 计算属性
const totalAgents = computed(() => agentCount.value)

const filteredAgents = computed(() => {
  if (!sortedAgents.value || !Array.isArray(sortedAgents.value)) {
    return []
  }
  
  let result = [...sortedAgents.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const searchResult = searchAgents(searchQuery.value)
    result = searchResult || []
  }
  
  // 分类过滤
  if (selectedCategory.value) {
    result = result.filter(agent => agent.category === selectedCategory.value)
  }
  
  // 手动排序（如果需要不同于默认的排序）
  if (sortBy.value !== 'createdAt') {
    result = [...result].sort((a, b) => {
      switch (sortBy.value) {
        case 'updatedAt':
          return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
        case 'name':
          return a.name.localeCompare(b.name)
        case 'author':
          return a.author.localeCompare(b.author)
        default:
          return 0
      }
    })
  }
  
  return result
})

const totalPages = computed(() => {
  return Math.ceil(filteredAgents.value.length / pageSize.value)
})

const paginatedAgents = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredAgents.value.slice(start, end)
})

// 监听搜索和筛选变化，重置分页
watch([searchQuery, selectedCategory, sortBy], () => {
  currentPage.value = 1
})

// 监听分页数据变化，执行动画
watch(paginatedAgents, async () => {
  await nextTick()
  animateListEnter('.agent-card-item')
})

// 生命周期
onMounted(async () => {
  // 加载智能体数据
  await loadAgentsData()
  
  // 加载分类数据
  await loadCategoriesData()
  
  // 页面进入动画
  await nextTick()
  animatePageEnter('.home-page')
  
  // 如果有错误，显示提示
  if (error.value) {
    ElMessage.error('加载智能体数据失败')
  }
})

/**
 * 处理注册提交
 */
async function handleRegisterSubmit(data: CreateAgentInput) {
  try {
    console.log('🎯 [HomePage] 接收到注册提交数据:', JSON.stringify(data, null, 2))
    console.log('🎯 [HomePage] 调用addAgent函数')
    
    await addAgent(data)
    
    console.log('✅ [HomePage] 智能体注册成功')
    ElMessage.success('智能体注册成功！')
  } catch (error) {
    console.error('❌ [HomePage] 注册智能体失败:', error)
    ElMessage.error('注册失败，请重试')
  }
}

/**
 * 处理编辑智能体
 */
function handleEditAgent(agent: Agent) {
  selectedAgent.value = agent
  registerDialogVisible.value = true
  console.log('打开编辑对话框:', agent)
}

/**
 * 打开注册对话框（重写以确保清空selectedAgent）
 */
function openRegisterDialog() {
  selectedAgent.value = null
  registerDialogVisible.value = true
}

/**
 * 处理编辑提交
 */
async function handleEditSubmit(editedAgent: Agent) {
  try {
    console.log('提交编辑的智能体数据:', editedAgent)
    
    // 调用后端API更新智能体信息
    const result = await updateAgent(editedAgent.id, editedAgent)
    
    if (result.success) {
      ElMessage.success('智能体信息更新成功')
      registerDialogVisible.value = false
      selectedAgent.value = null
      
      // 刷新数据
      await loadAgentsData()
    } else {
      ElMessage.error(result.error || '更新失败，请重试')
    }
  } catch (error: any) {
    console.error('更新智能体失败:', error)
    ElMessage.error(error.message || '更新失败，请重试')
  }
}

/**
 * 处理删除智能体
 */
function handleDeleteAgent(agent: Agent) {
  selectedAgent.value = agent
  openDeleteConfirmDialog(agent)
}

/**
 * 处理删除确认
 */
async function handleDeleteConfirm(agentId: string) {
  try {
    await deleteAgent(agentId)
    selectedAgent.value = null
    ElMessage.success('智能体删除成功')
  } catch (error) {
    console.error('删除智能体失败:', error)
    ElMessage.error('删除失败，请重试')
  }
}

/**
 * 处理导出智能体
 */
async function handleExportAgent(agent: Agent) {
  try {
    animateButtonClick('.export-btn')
    const data = await exportData()
    if (data) {
      // 创建下载链接
      const blob = new Blob([data], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `agent-${agent.name}-${Date.now()}.json`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
      ElMessage.success('智能体导出成功')
    }
  } catch (error) {
    console.error('导出智能体失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

/**
 * 处理复制智能体链接
 */
function handleCopyAgent(agent: Agent) {
  ElMessage.success(`已复制 ${agent.name} 的分享链接到剪贴板`)
  console.log('复制智能体链接:', agent.shareUrl)
}

/**
 * 处理分页大小变化
 */
function handleSizeChange(newSize: number) {
  pageSize.value = newSize
  currentPage.value = 1
}

/**
 * 处理网络错误重试
 */
async function handleRetry() {
  if (networkError.value?.retry) {
    await retryRequest(networkError.value.retry)
  } else {
    // 默认重试加载数据
    await retryRequest(loadAgentsData)
  }
}

/**
 * 打开标签管理对话框
 */
function openTagManagementDialog() {
  tagManagementDialogVisible.value = true
}

/**
 * 打开分类管理对话框
 */
function openClassifyManagementDialog() {
  classifyManagementDialogVisible.value = true
}

/**
 * 处理标签更新事件
 */
function handleTagsUpdated(tags: any[]) {
  console.log('标签已更新:', tags)
  ElMessage.success('标签数据已更新')
}

/**
 * 加载分类数据
 */
async function loadCategoriesData() {
  try {
    // 从classify.json文件加载数据
    const response = await fetch('/classify.json')
    if (response.ok) {
      const data = await response.json()
      if (data.classifies && Array.isArray(data.classifies)) {
        // 将分类数据转换为categories格式
        categories.value = data.classifies.map((classify: any) => ({
          label: classify.label,
          value: classify.value
        }))
      }
    } else {
      console.log('classify.json文件不存在，使用默认分类')
    }
  } catch (error) {
    console.error('加载分类数据失败:', error)
    // 保持默认分类数据
  }
}

/**
 * 处理分类更新事件
 */
function handleClassifiesUpdated(classifies: any[]) {
  console.log('分类已更新:', classifies)
  
  // 更新categories数据
  categories.value = classifies.map((classify: any) => ({
    label: classify.label,
    value: classify.value
  }))
}

/**
 * 更新分类数量显示
 */
function updateClassifyCount(count: number) {
  // 分类数量通过categories.value.length自动更新显示
  console.log('分类数量已更新为:', count)
}
</script>

<style scoped>
.home-page {
  position: relative;
  background: linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 50%, #16213e 100%);
  overflow-x: hidden;
  height: 100vh;
}

/* 背景动画层 */
.background-layer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;
}

.cyber-grid {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: 
    linear-gradient(rgba(50, 236, 138, 0.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(50, 236, 138, 0.1) 1px, transparent 1px);
  background-size: 50px 50px;
  animation: gridMove 20s linear infinite;
}

@keyframes gridMove {
  0% { transform: translate(0, 0); }
  100% { transform: translate(50px, 50px); }
}

.floating-particles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at 20% 50%, rgba(50, 236, 138, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 107, 107, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 40% 80%, rgba(0, 255, 127, 0.1) 0%, transparent 50%);
  animation: particleFloat 15s ease-in-out infinite;
}

@keyframes particleFloat {
  0%, 100% { transform: translateY(0) rotate(0deg); }
  33% { transform: translateY(-20px) rotate(120deg); }
  66% { transform: translateY(10px) rotate(240deg); }
}

/* 主要内容 */
.main-content {
  position: relative;
  z-index: 1;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

/* 页面头部 */
.page-header {
  margin-bottom: 40px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
}

.logo-section {
  flex: 1;
}

.site-title {
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.title-text {
  font-size: 2.5rem;
  font-weight: 700;
  background: linear-gradient(45deg, #32ec8a, #28c470);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 0 20px rgba(50, 236, 138, 0.3);
}

.title-subtitle {
  font-size: 1rem;
  color: rgba(255, 255, 255, 0.7);
  font-weight: 400;
  letter-spacing: 2px;
}

.header-actions {
  display: flex;
  gap: 16px;
}

.register-btn {
  background: linear-gradient(45deg, #32ec8a, #28c470);
  border: none;
  font-weight: 600;
  padding: 12px 24px;
  transition: all 0.3s ease;
}

.register-btn:hover {
  background: linear-gradient(45deg, #2dd47a, #25b366);
  box-shadow: 0 0 20px rgba(50, 236, 138, 0.4);
  transform: translateY(-2px);
}

.management-btn {
  background: rgba(50, 236, 138, 0.1);
  border: 1px solid rgba(50, 236, 138, 0.3);
  color: #32ec8a;
  font-weight: 500;
  padding: 12px 20px;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.management-btn:hover {
  background: rgba(50, 236, 138, 0.2);
  border-color: #32ec8a;
  color: #ffffff;
  box-shadow: 0 0 15px rgba(50, 236, 138, 0.3);
  transform: translateY(-2px);
}

.management-btn .el-icon {
  margin-right: 6px;
}

/* 搜索区域 */
.search-section {
  margin-bottom: 30px;
}

.search-container {
  display: flex;
  flex-direction: row;
  gap: 16px;
}

.search-input {
  width: 400px;
}

/* Element Plus 输入框样式现在由 global.scss 统一管理 */

.filter-bar {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 16px;
}

.category-select,
.sort-select {
  width: 300px;
}

/* Element Plus 选择器样式现在由 global.scss 统一管理 */

/* 统计信息 */
.stats-section {
  margin-bottom: 30px;
}

.stats-container {
  display: flex;
  justify-content: center;
  gap: 40px;
  flex-wrap: wrap;
}

.stat-item {
  text-align: center;
  padding: 16px 24px;
  background: rgba(50, 236, 138, 0.1);
  border: 1px solid rgba(50, 236, 138, 0.3);
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.stat-number {
  font-size: 2rem;
  font-weight: 700;
  color: #32ec8a;
  text-shadow: 0 0 10px rgba(50, 236, 138, 0.4);
}

.stat-label {
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.7);
  margin-top: 4px;
}

/* 智能体区域 */
.agents-section {
  margin-bottom: 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: #ffffff;
  margin: 0;
}

.view-controls {
  display: flex;
  gap: 8px;
}

/* Element Plus 按钮样式现在由 global.scss 统一管理 */

/* 加载状态 */
.loading-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.skeleton-item {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  padding: 20px;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #ffffff;
}

.empty-icon {
  margin-bottom: 20px;
  color: rgba(255, 255, 255, 0.3);
}

.empty-title {
  font-size: 1.5rem;
  margin-bottom: 12px;
  color: #ffffff;
}

.empty-description {
  font-size: 1rem;
  color: rgba(255, 255, 255, 0.6);
  margin-bottom: 24px;
}

.empty-action {
  background: linear-gradient(45deg, #32ec8a, #28c470);
  border: none;
}

/* 智能体容器 */
.agents-container.view-grid .agents-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.agents-container.view-list .agents-grid {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 卡片动画 */
.agent-card-enter-active {
  transition: all 0.5s ease;
}

.agent-card-leave-active {
  transition: all 0.3s ease;
}

.agent-card-enter-from {
  opacity: 0;
  transform: translateY(30px) scale(0.9);
}

.agent-card-leave-to {
  opacity: 0;
  transform: translateX(-30px) scale(0.9);
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

/* Element Plus 分页样式现在由 global.scss 统一管理 */

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    padding: 16px;
  }
  
  .agents-container.view-grid .agents-grid {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .title-text {
    font-size: 2rem;
  }
  
  .filter-bar {
    flex-direction: column;
    align-items: center;
  }
  
  .stats-container {
    gap: 20px;
  }
  
  .section-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .agents-container.view-grid .agents-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}

@media (max-width: 480px) {
  .main-content {
    padding: 12px;
  }
  
  .title-text {
    font-size: 1.5rem;
  }
  
  .stat-item {
    padding: 12px 16px;
  }
  
  .stat-number {
    font-size: 1.5rem;
  }
}
</style>